<template>
  <div class="user-add-or-update">
    <el-drawer :title="this.rowData ? '编辑用户' : '新增用户'" size="820px" :visible.sync="drawer" custom-class="demo-drawer" direction="rtl">
      <div class="demo-drawer__content">
        <div :style="cardHeightStyle" class="rightScrollNone">
          <el-form size="mini" ref="vendorRuleForm" :model="dataForm" :rules="rules">
            <el-row>
              <el-col :span="24">
                <el-form-item label="用户名：" prop="name" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.name" type="text" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="手机号：" prop="phone" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.phone" type="text" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="姓名：" prop="create_user" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.create_user" type="text" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <!-- 2021/3/11新增地址 -->
              <el-col :span="24">
                <el-form-item label="地址：" prop="zone" :label-width="formLabelWidth">
                  <el-cascader ref="cascaderHandle" v-model="dataForm.zoneList" :props="{ checkStrictly: true }" :options="cityOptions" @change="areaChangeHandle" style="width: 100%" placeholder="请选择所属地区，可搜索" filterable clearable></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="绑定邮箱：" prop="email" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.email" autocomplete="off" class="my-email" style="width: calc(100% - 150px); z-index: 1000"></el-input>
                  <el-tag size="small" type="warning" v-if="dataForm.is_email == 0">未绑定</el-tag>
                  <el-tag size="small" type="success" v-else>已绑定</el-tag>
                  <el-button size="mini" type="primary" style="margin-left: 15px" :disabled="refNum < 301" @click="bandingEmailHandle()">绑定 </el-button>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-show="showNumInput">
                <el-form-item label="验证码：" prop="emailCode" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.emailCode" autocomplete="off" style="width: calc(100% - 120px)"></el-input>

                  <el-button size="mini" style="margin-left: 15px; width: 100px" v-if="showRefBtn" @click="bandingEmailHandle"> 重新发送 </el-button>
                  <el-button size="mini" style="margin-left: 15px; width: 100px" :disabled="true" v-else>{{ refNum }} 秒</el-button>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="所属角色：" prop="roles_id" :label-width="formLabelWidth">
                  <el-select v-model="dataForm.roles_id" placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="密码：" prop="password" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.password" :placeholder="rowData ? '不填写默认密码不变动' : '不填写默认密码Aa123456'" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="确认密码：" prop="isPassword" :label-width="formLabelWidth">
                  <el-input v-model="dataForm.isPassword" autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="学校管理：" prop="schools" :label-width="formLabelWidth">
                  <el-select v-model="dataForm.schools" multiple placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in schooloptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="状态：" prop="status" :label-width="formLabelWidth">
                  <el-select v-model="dataForm.status" placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <div class="demo-drawer__footer">
          <el-button size="mini" @click="cancelForm">取 消</el-button>
          <el-button size="mini" type="primary" :loading="loading" @click="dataFormSubmit">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import city from './city.json'
import { userAdd, userEdit, nameCheck, schoollist } from '@/api/system/user.js'
import { emailSendCode, emailConfirm } from '@/api/api.js'
import { isMobile, isEmail, notHavNumAndSymbol, isPassword } from '@/utils/validate.js'
export default {
  data() {
    var validaName = (rule, value, callback) => {
      if (value && !notHavNumAndSymbol(value)) {
        callback(new Error('用户名只能为汉字或字母'))
      } else {
        const id = this.dataForm.id
        const name = value
        nameCheck({ id, name }).then((res) => {
          if (res.code == 200) {
            callback()
          } else {
            callback(new Error('该用户名已存在'))
          }
        })
      }
    }
    var validaMobile = (rule, value, callback) => {
      if (value && !isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    var validaEmail = (rule, value, callback) => {
      if (value && !isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    var validaEmailCode = (rule, value, callback) => {
      if (this.showNumInput && value.trim() == '') {
        callback(new Error('验证码不能为空'))
      } else if (this.showNumInput && value.trim() != '') {
        if (this.dataForm.is_email == 0) {
          emailConfirm({ code: this.dataForm.emailCode, email: this.dataForm.email })
            .then((res) => {
              if (res.code == 200) {
                clearTimeout(this.timeOutCount)
                this.dataForm.is_email = 1
                this.showRefBtn = true
                this.showNumInput = false
                this.dataForm.emailCode = ''
                this.refNum = 60 * 5 + 1
                callback()
              } else {
                callback(new Error('验证码错误'))
              }
            })
            .catch((res) => {
              callback(new Error('验证码错误'))
            })
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validaPassword = (rule, value, callback) => {
      if (value && !isPassword(value)) {
        callback(new Error('密码6~20位 必须含大写字母、小写字母、数字'))
      } else {
        callback()
      }
    }
    var validaIsPassword = (rule, value, callback) => {
      if (value && this.dataForm.password != value) {
        callback(new Error('两次输入密码值不相等'))
      } else {
        callback()
      }
    }
    return {
      cityOptions: city,
      schooloptions: [],
      timeOutCount: 0,
      showNumInput: false,
      showRefBtn: false,
      refNum: 0,
      dataForm: {
        id: '',
        name: '', // 用户名
        create_user: '',
        phone: '', //手机号
        email: '', //邮箱
        is_email: 0,
        roles_id: '', // 角色
        password: '', //密码
        isPassword: '', //确定密码
        status: 1, //状态
        emailCode: '',
        schools: '', // 可多选管理的校区
        zoneList: [], //地区集合
        zone: '', // 具体地址
      },
      rowData: null,
      //cityOptions: citys.options,
      formLabelWidth: '95px',
      loading: false,
      drawer: false,
      statusOptions: [
        { label: '激活', value: 1 },
        { label: '冻结', value: 0 },
      ],
      roleOptions: [],
      rules: {
        name: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { validator: validaName, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validaMobile, trigger: 'blur' },
        ],
        roles_id: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
        password: [{ validator: validaPassword, trigger: 'blur' }],
        isPassword: [{ validator: validaIsPassword, trigger: 'blur' }],
        email: [{ validator: validaEmail, trigger: 'blur' }],
        emailCode: [{ validator: validaEmailCode, trigger: 'blur' }],
        schools: [{ required: true, message: '请选择管理的校区', trigger: 'change' }],
        zone: [{ required: true, message: '请选择地址', trigger: 'change' }],
      },
    }
  },
  computed: {
    cardHeightStyle() {
      let documentClientHeight = document.body.clientHeight
      const height = documentClientHeight - 80 - 80
      return {
        height: height + 'px',
        'overflow-y': 'scroll',
        'padding-right': '20px;',
      }
    },
  },
  methods: {
    areaChangeHandle() {
      this.$refs.cascaderHandle.dropDownVisible = false
      const zone = this.dataForm.zoneList.join('/')
      this.dataForm.zone = zone
    },
    getshcoolselect() {
      schoollist({})
        .then((res) => {
          this.schooloptions = res.data
          this.schooloptions.forEach((item, index) => {
            item.label = item.name
            item.value = item.id
          })
        })
        .catch((e) => {})
    },
    showCodeInputHandle() {
      this.dataForm.is_email = 0
      this.refNum -= 1
      this.showNumInput = true
      this.showRefBtn = false
      this.timeOutCount = setTimeout(this.bandingEmailHandle, 1000) //保存定时器的句柄，方便清除定时器
    },
    //邮箱绑定 xiang_gao@idc518.cn
    bandingEmailHandle() {
      if (!this.dataForm.email.trim()) {
        this.$message.error('请先填写邮箱！')
        return
      }
      if (this.refNum == 0) {
        this.showRefBtn = true
        this.refNum = 60 * 5 + 1
      } else {
        if (this.refNum < 301) {
          this.showCodeInputHandle()
        } else {
          emailSendCode({ email: this.dataForm.email })
            .then((res) => {
              if (res.code == 200) {
                this.showCodeInputHandle()
                this.$message.success('发送成功')
              }
            })
            .catch((res) => {
              this.$message.error('发送失败')
            })
        }
      }
    },

    reportAdd(params) {
      if (this.dataForm.password.trim() == '') {
        params.password = 'Aa123456'
      }
      return userAdd(params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },
    reportUpdate(params) {
      return userEdit(params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },
    dataFormSubmit() {
      this.$refs.vendorRuleForm.validate((flag) => {
        if (flag) {
          const data = this.dataForm
          var request = this.rowData ? this.reportUpdate(data) : this.reportAdd(data)
          request
            .then((d) => {
              this.cancelForm()
              this.$emit('refreshList')
            })
            .catch((d) => {
              this.cancelForm()
            })
        }
      })
    },
    cancelForm() {
      this.cleanInfo()
      this.loading = false
      this.drawer = false
    },
    open(row, role) {
      if (this.drawer) {
        return
      }
      this.dataForm.zoneList = []
      this.roleOptions = role
      this.rowData = row || null
      this.drawer = true
      this.openHook()
      this.getshcoolselect()
    },
    clearData() {
      this.$refs.vendorRuleForm.resetFields()
    },
    cleanInfo() {
      this.dataForm.zoneList = []
      clearTimeout(this.timeOutCount)
      this.dataForm.emailCode = ''
      this.dataForm.is_email = 0
    },
    openHook() {
      this.$nextTick((a) => {
        this.showNumInput = false
        this.refNum = 60 * 5 + 1
        this.clearData()
        if (this.rowData) {
          // 修改
          for (let key in this.dataForm) {
            console.log(key)
            if (key == 'zoneList') {
              this.dataForm[key] = this.rowData.zone.split('/')
            } else if (key == 'schools') {
              this.dataForm[key] = JSON.parse(this.rowData[key])
            } else if (key == 'roles_id') {
              this.dataForm[key] = this.rowData.roles
            } else if (key != 'emailCode' && key != 'schools') {
              this.dataForm[key] = this.rowData[key]
            }
          }
        } else {
          this.loading = false
        }
      })
    },
  },
}
</script>
<style lang="scss">
.user-add-or-update {
  .el-tag {
    position: relative;
    right: 5px;
    z-index: 1;
    height: 40px;
    line-height: 40px;
    border-radius: 0 5px 5px 0;
    padding-left: 15px;
  }

  .my-email {
    .el-input__inner {
      border-radius: 5px 0 0 5px;
    }
  }
}

/*

  */

.fileInput {
  padding-right: 0;
}
</style>
